{% extends "admin/base.html" %}

{% block content %}
<div class="content-header">
    <h1>终端</h1>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5>服务器终端</h5>
            </div>
            <div class="card-body">
                <div class="terminal-container">
                    <div id="terminal-output" class="terminal-output bg-dark text-light p-3 mb-3" style="height: 500px; overflow-y: auto; border-radius: 5px; font-family: monospace;"></div>
                    <div class="input-group">
                        <span class="input-group-text bg-dark text-light" id="prompt-span">$</span>
                        <input type="text" id="terminal-input" class="form-control" placeholder="输入命令..." autocomplete="off">
                        <button class="btn btn-primary" type="button" id="terminal-submit">执行</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    const terminalOutput = document.getElementById('terminal-output');
    const terminalInput = document.getElementById('terminal-input');
    const terminalSubmit = document.getElementById('terminal-submit');
    const promptSpan = document.getElementById('prompt-span');
    
    // 初始化终端显示
    terminalOutput.innerHTML = '<div>欢迎使用服务器终端！</div><div>请输入命令开始操作。</div><div>&nbsp;</div>';
    
    // 滚动到底部
    terminalOutput.scrollTop = terminalOutput.scrollHeight;
    
    // 获取当前路径
    function getCurrentPath() {
        return fetch('/terminal_execute', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ command: 'pwd' })
        })
        .then(response => response.json())
        .then(data => {
            if (data.output) {
                return data.output.trim();
            }
            return '~';
        })
        .catch(error => {
            return '~';
        });
    }
    
    // 更新提示符
    function updatePrompt() {
        getCurrentPath().then(path => {
            promptSpan.textContent = `${path}$`;
        });
    }
    
    // 初始化提示符
    updatePrompt();

    // 执行命令函数
    function executeCommand() {
        const command = terminalInput.value.trim();
        if (!command) return;

        // 显示用户输入的命令
        const commandLine = document.createElement('div');
        commandLine.innerHTML = `<span class="text-success">${promptSpan.textContent}</span> ${command}`;
        terminalOutput.appendChild(commandLine);

        // 清空输入框
        terminalInput.value = '';

        // 发送请求到后端执行命令
        fetch('/terminal_execute', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ command: command })
        })
        .then(response => response.json())
        .then(data => {
            // 显示命令输出
            const outputLine = document.createElement('div');
            outputLine.className = 'terminal-line';
            outputLine.innerHTML = data.output.replace(/\n/g, '<br>');
            terminalOutput.appendChild(outputLine);
            
            // 滚动到底部
            terminalOutput.scrollTop = terminalOutput.scrollHeight;
            
            // 更新提示符（对于会改变路径的命令）
            if (command.startsWith('cd ')) {
                setTimeout(updatePrompt, 100);
            }
        })
        .catch(error => {
            const errorLine = document.createElement('div');
            errorLine.className = 'terminal-line text-danger';
            errorLine.innerHTML = `错误: ${error.message}`;
            terminalOutput.appendChild(errorLine);
            
            // 滚动到底部
            terminalOutput.scrollTop = terminalOutput.scrollHeight;
        });
    }

    // 绑定回车键事件
    terminalInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            executeCommand();
        }
    });

    // 绑定按钮点击事件
    terminalSubmit.addEventListener('click', executeCommand);

    // 聚焦到输入框
    terminalInput.focus();
</script>
{% endblock %}